var state = {};
var story = null;

function load(data, textStatus) {
  story = data
  story.cache = {}
  // Compile the pages in the story.
  for (i in story.pages) {
    var body = ("var p = []; with(state) {"
      + story.pages[i]._value + "} return p.join('');");
    try {
      story.cache[story.pages[i].id] = new Function('state', body);
    } catch (e) {
      alert(e);
    }
  }
  go(story.pages[0].id);
}

function choose() {  // Call one of the arguments at random.
  if (arguments.length == 0) {
    alert('No arguments passed to choose().');
  } else {
    choice = Math.floor(Math.random() * arguments.length);
    arguments[choice]();
  }
}

function go(key) {
  $('#view').fadeOut('fast', function() {
    try {
      var fn = story.cache[key];
      var html;
      if (fn != undefined) {
        html = fn(state);
        if (story.cache['Status']) {
          html += '<hr />' + story.cache['Status'](state);
        }
      } else {
        html = '<p>There is no page ' + key + '.</p>';
      }
      $('#view').html(html);
    } catch (e) {
      $('#view').html('<p>Error at ' + key + ': ' + e + '</p>');
    } finally {
      $('#view').fadeIn('fast');
    }
  });
}
